<?

namespace core;

use core\Validator;
use PDO;
use core\Db;

class Model extends Db
{
    public static $table = '';
    
    public static function __callStatic($method,$argv)
    {
        $handler = new static;
        $handler->query['table']= static::$table;  
        loger($method);
        return $handler->$method(...$argv);
    }

    public static function u($model)
    {
        if (!$config = config('model.'.$model)) {
            apiErr('模型不存在');
        }

        $class= '\\app\\model\\'.ucfirst($model);
        $handler = new $class;
        $handler->query['table'] = $config['table'];
        $handler->config = $config;
        $handler->apiData = app('curr')->data;
        return $handler;
    }

    public function check($action)
    {
        foreach ($this->config['fields'] as $k => $v) {
            $key = $v[1].'|'.$k;
            $rule[$key] = $v[0];
            if ($v[2]??null) {
                $rule[$key] = $v[0].'|'.$v[2];
            }
            if (in_array($k,$this->config['action'][$action]??[])) {
                $rule[$key].='|required';
            }
        }

        if ($err=Validator::run($this->apiData,$rule)->error) {
            apiErr($err);
        }

        switch ($action) {
            case 'insert':
                $this->apiData=array_intersect_key($this->apiData,$this->config['fields']);
                break;
            
            default:
                // code...
                break;
        }

        return $this;
    }

}
